package com.qf.openapi.web.master.controller;

import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.service.UserService;
import com.qf.openapi.web.master.utils.Constants;
import com.qf.openapi.web.master.vo.ResultVo;
import com.qf.openapi.web.master.vo.TableVo;
import com.qf.openapi.web.master.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController<T> {
    @Autowired
    UserService userService;


    @PostMapping("/login")
    public ResultVo login(String username, String password, String capchar, String choose, HttpSession httpSession, HttpServletRequest request, HttpServletResponse response) {
        //打印日志
        String attribute = (String) httpSession.getAttribute("captcha");
        log.info("username={},password={},用户输入的验证码为{},系统生成的验证码为={}", username, password, capchar, attribute);
        //1.处理验证码是否正确

        if (!attribute.equals(capchar)) {
            ResultVo result = new ResultVo("验证码不正确", Constants.DEFAULT);
            return result;
        }
        //2.调用service的方法进行登录验证
        User user = userService.login(username, password);
        //
        log.info("返回的user对象为{}", user);
        if (user == null) {
            ResultVo result = new ResultVo("登陆失败", Constants.DEFAULT);
            log.info("code={}", result);
            return result;
        } else {
            httpSession.setAttribute(Constants.SISSION_USER_KEY, user);
            ResultVo result = new ResultVo("登录成功", Constants.SUCCESS);
            if ("on".equals(choose)) {
                String value = username + "-" + password;
                //生产用于免登陆的cookie
                Cookie c1 = new Cookie(Constants.USER_TOKEN, value);
                c1.setPath("/");
                c1.setMaxAge(15 * 24 * 60 * 60);
                log.debug("cookie={}", value);
                response.addCookie(c1);

            }

            log.info("code={}", result);

            return result;
        }


    }

    /**
     * @param userVo
     * @param session
     * @return
     */
    @PostMapping("/insert")
    public ResultVo insertUser(UserVo userVo, HttpSession session) throws IOException {
        String attribute = (String) session.getAttribute("captcha");
        log.info("UserVo={},系统生成的验证码为={}", userVo, attribute);
        //1.处理验证码是否正确

        if (!attribute.equals(userVo.getCapchar())) {
            ResultVo result = new ResultVo("验证码不正确", Constants.DEFAULT);
            return result;
        }

        //2.
        String path = session.getServletContext().getRealPath(Constants.UPLOAD_PATH);
        ResultVo resultVo = userService.insert(userVo, path);
        return resultVo;

    }

    @GetMapping("/current")
    public ResultVo getCurrentUser(HttpSession session) {

        User user = (User) session.getAttribute(Constants.SISSION_USER_KEY);

        if (!(user == null)) {
            return new ResultVo("获取成功", 1, user);
        } else {
            return new ResultVo("获取失败", -1);
        }
    }

    /**
     * 登录用户的头像
     */
    @GetMapping("/pic")
    public void getPic(HttpSession session, HttpServletResponse response) throws IOException {
        User user = (User) session.getAttribute(Constants.SISSION_USER_KEY);

        if (!(user == null)) {
            String s = user.getPhotopath();
            String path = session.getServletContext().getRealPath(Constants.UPLOAD_PATH);
            String fileName = path + File.separator + s;
            log.debug("获取登录用户的头像，文件路径为={}", fileName);
            IOUtils.copy(new FileInputStream(fileName), response.getOutputStream());
        } else {
            return;
        }
    }

    /**
     * @param username
     * @return
     */
    @GetMapping("/checkusername")
    public ResultVo checkUserName(String username) {

        ResultVo resultVo = userService.checkUserName(username);

        return resultVo;
    }

    /**
     * @param page  页号
     * @param limit 页大小
     * @return
     */
    @GetMapping("/getalluser")
    public TableVo<User> getAllUser(Integer page, Integer limit) {
        log.debug("查询用户page={},limit={}", page, limit);
        TableVo<User> table = userService.getAllUserByPage(page, limit);
        log.debug("TableVo的结果为={}", table);
        return table;
    }

    @GetMapping("/getalluserbypagehelper")
    public TableVo<User> getUserbypageHelper(Integer page, Integer limit) {
        TableVo<User> result = userService.getAllUserByPageHelper(page, limit);

        return result;
    }

    @PostMapping("/del")
    public ResultVo deleteUser(Integer[] ids) {
        for (Integer id : ids) {
            log.debug("删除的id为{}", id);
        }
        return userService.deleteUserById(ids);

    }

    /**
     * 添加用户
     *
     * @param userVo
     * @return
     */
    @PostMapping("/add")
    public ResultVo addUser(UserVo userVo) {
        log.debug("添加用户,姓名={},密码={},生日={}", userVo.getUsername(), userVo.getPassword(), userVo.getBirthday());
        ResultVo resultVo = userService.addUser(userVo);
        return resultVo;
    }

    @PostMapping("/update")
    public ResultVo updateUser(UserVo userVo) {
        log.debug("修改的数据的名字为={}", userVo.getUsername());
        return userService.updateUser(userVo);
    }

    @GetMapping("/getusersbycontditions")
    public TableVo<User> getUsersByContditions(Integer page, Integer limit, UserVo userVo){
        log.debug("page={},limit={},userVo=",page,limit,userVo);
        TableVo<User> able  = userService.getUsersByContditions(page,limit,userVo);
        able.setCode(0);
        return able;
    }

    /**
     *
     * @return
     */
    @GetMapping("/export")
    public ResultVo export() throws Exception {
        //1.生成文件
        //2.返回文件
        return userService.export();
    }

}

